package com.ruoyi.register.service;


import com.ruoyi.register.mapper.MerchantRegisterMapper;
import com.ruoyi.register.po.BusinessLicensePo;
import com.ruoyi.register.po.MerchantUserPo;
import com.ruoyi.register.vo.GoodsVo;
import com.ruoyi.register.vo.MerchantUserVo;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import utils.BankCardUtils;
import utils.IdCardUtils;
import utils.IdWorker;
import utils.Result;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: 程昱轩
 * @Description: TODO
 * @DateTime: @date 2023/2/23 14:29
 **/
@Service
public class MerchantRegisterService {
    @Resource
    private MerchantRegisterMapper merchantRegisterMapper;
    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Resource
    private RestHighLevelClient restHighLevelClient;
    @Resource
    private IdWorker idWorker;

    public Result merchantRegister(MerchantUserVo merchantUserVo) {
        MerchantUserVo merchantUserPo=merchantRegisterMapper.checkUsername(merchantUserVo);
        if (null!=merchantUserPo){
            return Result.error(1004,"用户名已存在");
        }

        boolean idCardFlag = IdCardUtils.checkIdCard(merchantUserVo.getUsername(), merchantUserVo.getIdCard());
        if (!idCardFlag) {
            return Result.error(1001, "身份证信息错误");
        }
        boolean bankCardFlag = BankCardUtils.BankCard(merchantUserVo.getUsername(), merchantUserVo.getBankCard());
        if (!bankCardFlag) {
            return Result.error(1002, "银行卡信息错误");
        }
        BusinessLicensePo businessLicense=merchantRegisterMapper.findByBusinessLicense(merchantUserVo);
        if (null == businessLicense) {
            return Result.error(1003, "营业执照信息错误");
        }
        merchantUserVo.setPassword(bCryptPasswordEncoder.encode(merchantUserVo.getPassword()));
        merchantRegisterMapper.merchantRegister(merchantUserVo);
        return Result.success();
    }
//
    public Result importData(List<GoodsVo> list) throws IOException {
        for (GoodsVo goodsVo : list) {
            merchantRegisterMapper.importData(goodsVo);
            IndexRequest indexRequest = new IndexRequest("goods","goods");
            indexRequest.id(idWorker.nextId()+"");
            HashMap<String , Object> map = new HashMap<>();
            map.put("title",goodsVo.getTitle());
            map.put("img",goodsVo.getImg());
            indexRequest.source(map);
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        }
        return Result.success();
    }
}
